package com.zwh.rocketmq.demo.transaction;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zwh
 * @date 2024-1-22 12:00
 */
@Service
public class ProductOrderService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 模拟事务消息
     * 参考链接：https://my.oschina.net/zlt2000/blog/4522907
     * @param orderNo
     */
    public void delete(String orderNo) {
        //如果订单存在且状态为有效，进行业务处理
//        Order order = orderMapper.selectByNo(orderNo);
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("orderId", 1);
        orderMap.put("userId", 2);
        // 订单金额
        orderMap.put("amount", "100");

        String destination = "add-amount";
        String tags = "tag1";
        if (StringUtils.isNotBlank(tags)) {
            // 带tag的消息，直接在topic后面加上":tag"， 底层会进行自动转换
            destination = destination + ":" + tags;
        }

        String transactionId = UUID.randomUUID().toString();
        Message<Map<String, Object>> message1 = MessageBuilder.withPayload(orderMap)
                .setHeader(RocketMQHeaders.KEYS, orderMap.get("orderId"))
                .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                //一般事务消息都会设置一个本地事务关联的唯一ID，用来做本地事务回查的校验。
                .build();
        rocketMQTemplate.sendMessageInTransaction(destination, message1, orderMap);

    }


}
